package cn.glinks.liuhe.api.factory;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import cn.glinks.liuhe.baserx.BaseResponse;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import static okhttp3.internal.Util.UTF_8;

/**
 * Des:MobuGsonResponseBodyConverter,处理ResponseBody
 *
 * @author MarsBlade of Cyh
 * @created 2017-03-16 14:11
 */
final class GlkGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GlkGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        // 自定义的转换方式
        String response = value.string();

        // 打印响应信息
        // LogUtils.logd(response);

        // 转换为BaseResponse形式Json数据
        BaseResponse baseRespose = new BaseResponse();
        if (response.isEmpty()) {
            baseRespose.status = -1;
            baseRespose.msg = "MobuGsonResponseBodyConverter convert failed!";
            baseRespose.data = null;
        } else {
            baseRespose.status = 0;
            baseRespose.msg = response;
            baseRespose.data = null;
        }
        String newResponse = gson.toJson(baseRespose);

        // 将重新构建好的newResponse重新转换为Reader类型
        MediaType contentType = value.contentType();
        Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
        InputStream inputStream = new ByteArrayInputStream(newResponse.getBytes());
        Reader reader = new InputStreamReader(inputStream, charset);

        // 原有流程
        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
